﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;

namespace WebNavigationApi.Utils
{
    public class ImageHelper
    {
        public static Image UrlToImage(string url)
        {
            WebRequest webreq = WebRequest.Create(url);
            WebResponse webres = webreq.GetResponse();
            using (Stream stream = webres.GetResponseStream())
            {
                return (Bitmap)System.Drawing.Image.FromStream(stream);
            }
        }

        public static string ImageConvertBase64StringForJs(Image img, ImageFormat imageFormat = null)
        {
            if (img == null)
            {
                return "";
            }
            imageFormat = img.RawFormat ?? imageFormat ?? ImageFormat.Jpeg;
            using (MemoryStream ms = new MemoryStream())
            {
                img.Save(ms, img.RawFormat ?? ImageFormat.Jpeg);
                byte[] data = ms.ToArray();
                return Convert.ToBase64String(data);
            }
        }

        public static Image Base64StringConvertImageForJs(string base64)
        {
            if (string.IsNullOrEmpty(base64))
            {
                throw new ArgumentNullException("base64参数不能为空");
            }
            byte[] bytes = Convert.FromBase64String(base64);
            Image img = null;
            using (MemoryStream memStream = new MemoryStream(bytes))
            {
                img = Image.FromStream(memStream);
            }
            return img;
        }
    }
}
